package ch.areion.areionapp.sensor;

import ch.areion.areionapp.communication.Monitor;
import ch.areion.common.message.Module;
import ch.areion.common.message.Type;
import ch.areion.common.message.Version;
import ioio.lib.api.DigitalInput;
import ioio.lib.api.IOIO;
import ioio.lib.api.exception.ConnectionLostException;

public class IRSensor implements IIRSensor {
	/* Settings */
	private final static DigitalInput.Spec.Mode MODE = DigitalInput.Spec.Mode.PULL_DOWN;
	//private final static boolean ACTIVE = false;
	
	private IOIO ioio;
	
	/* Pins */
	private DigitalInput side;
	private DigitalInput frontLeft;
	private DigitalInput frontRight;
	
	/* Pin Defintion */
	private final static int SIDE = 22;
	private final static int FRONTLEFT = 23;
	private final static int FRONTRIGHT= 24;
	
	public IRSensor(IOIO ioio_) throws ConnectionLostException {
		this.ioio = ioio_;
		setup();
	}
	
	private void setup() throws ConnectionLostException {
		side = ioio.openDigitalInput(SIDE, MODE);
		frontLeft = ioio.openDigitalInput(FRONTLEFT, MODE);
		frontRight = ioio.openDigitalInput(FRONTRIGHT, MODE);
	}
	
	@Override
	public void disconnect() throws ConnectionLostException, InterruptedException
	{
		side.close();
		frontLeft.close();
		frontRight.close();
	}

	@Override
  public void waitUntil(IRS irs, boolean value) throws InterruptedException, ConnectionLostException {
		Monitor.getInstance().add(Version.V01, Type.INFO, Module.SENSOR,
				"Waiting for sensor " + irs.toString());
		switch(irs) {
			case SIDE:
				side.waitForValue(!value);
				break;
			case FRONTLEFT:
				frontLeft.waitForValue(!value);
				break;
			case FRONTRIGHT:
				frontRight.waitForValue(!value);
				break;
		}
//		Monitor.getInstance().add(Version.V01, Type.INFO, Module.SENSOR,
//				"Sensor " + irs.toString() + " switched.");
  }

	@Override
  public boolean read(IRS irs) throws InterruptedException, ConnectionLostException {
		boolean ret = true;
		switch(irs) {
			case SIDE:
				ret = side.read();
				break;
			case FRONTLEFT:
				ret = frontLeft.read();
				break;
			case FRONTRIGHT:
				ret = frontRight.read();
				break;
		}
//		Monitor.getInstance().add(Version.V01, Type.INFO, Module.SENSOR,
//				"Sensor " + irs.toString(), String.format("%b", ret));
	  return !ret;
  }

}
